#include "key.h"
//#include "system_stm32f10x.h"
#include "stm32f10x.h"
//#include "libc.h"

void key_init(void)
{
	GPIO_InitTypeDef  GPIO_InitStructure;
	
	/* Alientek MiniSTM32:  WK_UP-PA0  KEY1-PA15  KEY0-PC5 */

	GPIO_InitStructure.GPIO_Pin = KEY_SEL_PIN;	   //KEY0-PC5
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; 	
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	
	GPIO_Init(KEY_SEL_PORT, &GPIO_InitStructure);
	GPIO_SetBits(KEY_SEL_PORT, KEY_SEL_PIN);

	GPIO_InitStructure.GPIO_Pin = KEY_DEC_PIN;     //KEY1-PA15
	GPIO_Init(KEY_DEC_PORT, &GPIO_InitStructure);
	GPIO_SetBits(KEY_DEC_PORT, KEY_DEC_PIN);	
	
	GPIO_InitStructure.GPIO_Pin = KEY_INC_PIN;	   //WK_UP-PA0 
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; 	
	GPIO_Init(KEY_INC_PORT, &GPIO_InitStructure);
	GPIO_ResetBits(KEY_INC_PORT, KEY_INC_PIN);
}


//GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
#define read_key1()  GPIO_ReadInputDataBit(KEY_SEL_PORT, KEY_SEL_PIN)
#define read_key2()  GPIO_ReadInputDataBit(KEY_DEC_PORT, KEY_DEC_PIN)
#define read_key3()  GPIO_ReadInputDataBit(KEY_INC_PORT, KEY_INC_PIN)

char key_scan1(){
    static char state = 0;
    switch(state){
        case 0:
            state = 1;
        break;
        case 1:
            if(read_key1() == 0){
                state = 2;
                return 1;
            }
        break;
        case 2:
            if(read_key1() == 1){
                state = 0;
            }
        break;
    }
    
    return 0;
}


char key_scan2(){
    static char state = 0;
    switch(state){
        case 0:
            state = 1;
        break;
        case 1:
            if(read_key2() == 0){
                state = 2;
                return 1;
            }
        break;
        case 2:
            if(read_key2() == 1){
                state = 0;
            }
        break;
    }
    
    return 0;
}
char key_scan3(){
    static char state = 0;
    switch(state){
        case 0:
            state = 1;
        break;
        case 1:
            if(read_key3() == 1){
                state = 2;
                return 1;
            }
        break;
        case 2:
            if(read_key3() == 0){
                state = 0;
            }
        break;
    }
    
    return 0;
}

char  key_scan(){
    if(key_scan1()){
        return 1;
    }
    if(key_scan2()){
        return 2;
    }
    if(key_scan3()){
        return 3;
    }
    return 0;
}


